package hu.fic.weddingstorefinder.db.table;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.database.sqlite.SQLiteDatabase;

import hu.fic.weddingstorefinder.db.generatedtable.GeneratedDress;
import hu.fic.weddingstorefinder.utils.Constants;

public class Dress extends GeneratedDress {
	public Dress(SQLiteDatabase db, Activity activity) {
		super(db, activity);
	}
	
	public void processDressListFromJSON(JSONArray dressList) throws Exception {
		if (dressList.length() == 0) {
			return;
		}
		try {
			db.beginTransaction();
			for (int i = 0; i < dressList.length(); i++) {
				JSONObject dressObj = dressList.optJSONObject(i);
				this.clear();
				this.setCustomDressId(dressObj.optInt(Constants.JSON_ID));
				this.load();
				if (this.rowCount() > 0) {
					this.clear();
					//update drss with customid
					this.setCustomDressId(dressObj.optInt(Constants.JSON_ID));
					this.addCurrencyUpdate(dressObj.optString(Constants.JSON_CURRENCY));
					this.addCustomPOIIdUpdate(dressObj.optInt(Constants.JSON_POIID));
					this.addDressDescUpdate(dressObj.optString(Constants.JSON_DESCRIPTION));
					this.addDressStatusUpdate(dressObj.optInt(Constants.JSON_STATUS));
					this.addImageNameUpdate(dressObj.optString(Constants.JSON_IMAGENAME));
					this.addIsAvailableUpdate(dressObj.optInt(Constants.JSON_AVALIABLE));
					this.addPriceUpdate(dressObj.optInt(Constants.JSON_PRICE));
					this.update();
				} else {
					//add new dress:
					this.clear();
					this.setCustomDressId(dressObj.optInt(Constants.JSON_ID));
					this.setCurrency(dressObj.optString(Constants.JSON_CURRENCY));
					this.setCustomPOIId(dressObj.optInt(Constants.JSON_POIID));
					this.setDressDesc(dressObj.optString(Constants.JSON_DESCRIPTION));
					this.setDressStatus(dressObj.optInt(Constants.JSON_STATUS));
					this.setImageName(dressObj.optString(Constants.JSON_IMAGENAME));
					this.setIsAvailable(dressObj.optInt(Constants.JSON_AVALIABLE));
					this.setPrice(dressObj.optInt(Constants.JSON_PRICE));
					this.newRow();
				}
			}
			this.clear();
			//delete marked dressess:
			this.setDressStatus(Constants.DRESS_STATUS_TODELETE);
			this.load();
			Dress deleteTable = new Dress(db, activity);
			while (this.nextRow()) {
				deleteTable.setCustomDressId(this.getCustomDressId());
				deleteTable.delete();
				deleteTable.clear();
			}
			db.setTransactionSuccessful();
		} catch (Exception e) {
			throw e;
		} finally {
			db.endTransaction();
		}
		
	}
}